// 时间维度配置
const TIME_DIMENSIONS = {
    daily: {
        days: 1,
        format: 'YYYY-MM-DD'
    },
    weekly: {
        days: 7,
        format: 'YYYY-MM-DD'
    },
    monthly: {
        days: 30,
        format: 'YYYY-MM-DD'
    },
    yearly: {
        months: 12,
        format: 'YYYY-MM'
    }
};

// 调试函数
function debugLog(msg, data) {
    if (data === undefined) {
        node.warn(`DEBUG - ${msg}`);
    } else {
        node.warn(`DEBUG - ${msg}: ${JSON.stringify(data, null, 2)}`);
    }
}

// 验证测点配置
function validateMeasurementPoint(point, pointId) {
    // 检查dimensions对象是否存在
    if (!point.dimensions) {
        debugLog(`Missing dimensions object`, {
            pointId,
            currentConfig: point
        });
        return false;
    }

    // 检查所有必需的维度
    const dimensions = ['daily', 'weekly', 'monthly', 'yearly'];
    const missing = dimensions.filter(dim => !point.dimensions[dim]);
    
    if (missing.length > 0) {
        debugLog(`Invalid point configuration`, {
            pointId,
            missingDimensions: missing,
            currentConfig: point
        });
        return false;
    }
    return true;
}

// 工具函数：格式化日期
function formatDate(date, format) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    if (format === 'YYYY-MM-DD') {
        return `${year}-${month}-${day}`;
    }
    if (format === 'YYYY-MM') {
        return `${year}-${month}`;
    }
}

// 工具函数：获取日期范围
function getDateRange(currentDate, dimension) {
    const dates = [];
    const config = TIME_DIMENSIONS[dimension];
    
    if (dimension === 'yearly') {
        // 处理年维度（按月）
        for (let i = 0; i < config.months; i++) {
            const date = new Date(currentDate);
            date.setMonth(date.getMonth() - i);
            dates.push(formatDate(date, config.format));
        }
    } else {
        // 处理其他维度（按天）
        for (let i = 0; i < config.days; i++) {
            const date = new Date(currentDate);
            date.setDate(date.getDate() - i);
            dates.push(formatDate(date, config.format));
        }
    }
    
    return dates.sort();  // 按时间升序排序
}

// 主聚合函数
function aggregateDimensions(msg) {
    try {
        debugLog("Starting electric meter aggregation process");
        
        // 获取原始数据和测点配置
        const rawData = global.get('_ELECTRIC_STATISTICS_');
        const MEASUREMENT_POINTS = global.get('_ELECTRIC_POINTS_');
        
        // 验证原始数据
        if (!rawData) {
            debugLog("No electric statistics data found in global context");
            return msg;
        }
        
        // 验证测点配置
        if (!MEASUREMENT_POINTS) {
            debugLog("No electric measurement points configuration found in global context");
            return msg;
        }

        // 验证配置格式
        debugLog('Electric Measurement Points Raw Config', MEASUREMENT_POINTS);
        
        // 验证时间维度数据
        if (!rawData.byTimeDimension) {
            debugLog("Missing time dimension data", {
                hasTimeDimension: !!rawData.byTimeDimension
            });
            return msg;
        }
        
        const currentDate = new Date();
        const result = {};
        let totalProcessedPoints = 0;
        let invalidPoints = 0;
        
        // 遍历每个测点
        Object.keys(MEASUREMENT_POINTS).forEach(pointId => {
            const point = MEASUREMENT_POINTS[pointId];
            
            // 验证测点配置
            if (!validateMeasurementPoint(point, pointId)) {
                invalidPoints++;
                return;
            }
            
            result[pointId] = {};
            
            // 处理每个时间维度
            Object.keys(TIME_DIMENSIONS).forEach(dimension => {
                const dimensionId = point.dimensions[dimension];
                const dimensionData = rawData.byTimeDimension[dimension];
                
                // 初始化该维度的值为0
                result[pointId][dimensionId] = 0;
                
                if (!dimensionData) return;
                
                // 获取日期范围
                const dateRange = getDateRange(currentDate, dimension);
                
                // 遍历日期范围
                dateRange.forEach(date => {
                    if (dimensionData[date] && dimensionData[date][pointId]) {
                        const consumption = dimensionData[date][pointId].consumption;
                        if (typeof consumption === 'number' && consumption > 0) {
                            result[pointId][dimensionId] = Number((result[pointId][dimensionId] + consumption).toFixed(2));
                        }
                    }
                });
                
                debugLog(`Dimension Summary`, {
                    pointId,
                    dimension,
                    dimensionId,
                    total: result[pointId][dimensionId]
                });
            });
            
            totalProcessedPoints++;
        });
        
        debugLog('Aggregation Summary', {
            totalPoints: Object.keys(MEASUREMENT_POINTS).length,
            invalidPoints,
            processedPoints: totalProcessedPoints,
            pointsWithData: Object.keys(result).length
        });
        
        debugLog('Final Result', result);
        msg.payload = result;
        return msg;
        
    } catch (error) {
        debugLog("Error in aggregation", {
            message: error.message,
            stack: error.stack
        });
        return msg;
    }
}

// 设置为 Node-RED 函数节点的内容
return aggregateDimensions(msg); 